﻿using ConfExpert.Forms.Sistem;
using ConfExpert.Utility;
using DevExpress.XtraEditors;
using DevTeam;
using DevTeam.BaseForms;
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;

namespace ConfExpert.Core
{
    public partial class Login : DevLogin
    {
        public Login()
        {
            InitializeComponent();
            DevExpress.LookAndFeel.UserLookAndFeel.Default.SetSkinStyle("Office 2013");

            this.InitSession += Login_InitSession;
            this.InitApplication += Login_InitApplication;
            this.CheckUser += Login_CheckUser;
        }

        Session.DevApplication Login_InitApplication()
        {
            return new Session.DevApplication("ConfExpert", "ce.sqlite");
        }

        bool Login_CheckUser(string Username, string Password, string NewPassword)
        {
            Session.ServerAddress = "confexpert.karbel.com";
            ceGate.ceGateSoapClient gate = new ceGate.ceGateSoapClient();
            gate.Endpoint.Address = new System.ServiceModel.EndpointAddress(string.Format("http://{0}/ceGate/ceGate.asmx", Session.ServerAddress));

            SqlConnectionStringBuilder cnnStrBuilder = new SqlConnectionStringBuilder();
            DataSet dsCredentials = null;
            try
            {
                dsCredentials = gate.GetCredentials(Username, Password, Session.ServerAddress, Session.DatabasePostFix);
            }
            catch (Exception ex)
            {
                LogManager.LogToDB(ex);
                return false;
            }

            if (dsCredentials == null)
                return false;

            if (NewPassword != "")
            {
                string[] PasswordHashed = CryptoManager.GetSaltedHash(NewPassword);
                Session.DataManager.ExecuteNonQuery("UpdUserInfo", Username, PasswordHashed[0], PasswordHashed[1]);

                XtraMessageBox.Show("Parolanız başarıyla değiştirildi. Sonraki girişlerde yeni parolanızı kullanın.");
            }

            string connectionString = dsCredentials.Tables["ConnectionString"].Rows[0]["ConnectionString"].ToString();
            cnnStrBuilder.ConnectionString = connectionString;

            ConfExpert.Datasets.CustomConnectionString.SetConnection(cnnStrBuilder.ConnectionString);
            Session.DataManager = new DataManager(cnnStrBuilder.ConnectionString);

            try
            {

                DataRow dr = dsCredentials.Tables["User"].Rows[0];

                Session.CurrentUser = new User();
                Session.CurrentUser.UserId = (int)dr["UserId"];
                Session.CurrentUser.InitialUserId = Session.CurrentUser.UserId;
                Session.CurrentUser.DepartmentId = (int)dr["DepartmentId"];
                Session.CurrentUser.UserName = Username;
                Session.CurrentUser.Name = dr["Name"].ToString();
                Session.CurrentUser.Email = dr["Email"].ToString();
                Session.CurrentUser.PasswordHash = dr["PasswordHash"].ToStr();
                AppSession.Settings = PrgSettings.LoadSettings(dr["Settings"].ToString());
                AppSession.PrgSettingsOrg = PrgSettings.LoadSettings(dr["Settings"].ToString());
                AppSession.gleCustomer = dr["gleCustomer"].ToInt();
                AppSession.gleSeason = dr["gleSeason"].ToInt();
                AppSession.gleVendor = dr["gleVendor"].ToInt();

                RememberUser(Username);

                double EUR = 1, USD = 1, GBP = 1;
                List<string> exchange = new List<string>();
                foreach (DataRow dr2 in dsCredentials.Tables["Currency"].Rows)
                {
                    exchange.Add(dr2["Currency"].ToString() + ": " + dr2["Buying"].ToString());
                    string currency = dr2["Currency"].ToString();
                    double val = double.Parse(dr2["Buying"].ToString());
                    switch (currency)
                    {
                        case "EUR": EUR = val; break;
                        case "USD": USD = val; break;
                        case "GBP": GBP = val; break;
                    }
                }

                exchange.Add(String.Format("EUR/USD: {0:#.####}", EUR / USD));
                Session.GununKurlari = "* " + string.Join("  " + ((char)183) + "  ", exchange.ToArray());
                Session.Usd = USD; Session.Eur = EUR; Session.Gbp = GBP;

                DataRow[] serviceInfo = dsCredentials.Tables["Services"].Select("Id='Messenger'");
                if (serviceInfo.Length > 0)
                {
                    Session.MessengerUserName = serviceInfo[0]["Username"].ToStr();
                    Session.MessengerPassword = serviceInfo[0]["Password"].ToStr();
                }

                serviceInfo = dsCredentials.Tables["Services"].Select("Id='Unsped'");
                if (serviceInfo.Length > 0)
                {
                    AppSession.UnspedUsername = serviceInfo[0]["Username"].ToStr();
                    AppSession.UnspedPassword = serviceInfo[0]["Password"].ToStr();
                }

                serviceInfo = dsCredentials.Tables["Services"].Select("Id='Barsan'");
                if (serviceInfo.Length > 0)
                {
                    AppSession.BarsanUsername = serviceInfo[0]["Username"].ToStr();
                    AppSession.BarsanPassword = serviceInfo[0]["Password"].ToStr();
                }

                serviceInfo = dsCredentials.Tables["Services"].Select("Id='Dhl'");
                if (serviceInfo.Length > 0)
                {
                    AppSession.DhlUsername = serviceInfo[0]["Username"].ToStr();
                    AppSession.DhlPassword = serviceInfo[0]["Password"].ToStr();
                }

                Session.CurrentUser.SetYetki(dsCredentials.Tables["Yetki"]);


                return true;
            }

            catch (Exception Ex)
            {
                XtraMessageBox.Show("Sistem Hatası ! [Login]:" + Ex.ToString());
            }

            return false;
        }

        void Login_InitSession()
        {
            Dictionary<string, string> SavedLookups = new Dictionary<string, string>();
            SavedLookups.Add("V_Kumas", "CREATE TABLE [V_Kumas]( [ProductId] int PRIMARY KEY NOT NULL, [PhotoMikro] [BLOB], [Name] [varchar](500), [KVendorId] [int], [KCustomerId] [int], [KompozisyonId] [int], [FinishId] [int], [Konstruksiyon] [varchar](500), [KaliteId] [int], [KaliteAciklama] [varchar](500), [Desc7C] [varchar](500), [DescK] [varchar](500), [FabricTypeId] [int], [EnGrubu] [varchar](50), [DesenYonuId] [int], [DesenId] [int], [OrguId] [int], [Agirlik] [varchar](50), [Grup7CId] [int], [GrupESPId] [int], [Tags] [varchar](500), [RaporBoyuId] [int], [YTalimatId] [int], [Notes] [varchar](500), [CheckedOn] [datetime], [ModifiedOn] [datetime], [Hue] [real], [UserId] [int], [Deleted] [bit], [TS] [varbinary])");
            SavedLookups.Add("V_Aksesuar", "CREATE TABLE [V_Aksesuar]( [AksesuarId] [int], [PhotoMikro] [BLOB], [StokKod] [varchar](250), [AksSeriId] [int], [BrandId] [int], [ProductCategoryId] [int], [Etiket] [varchar](300), [Renk] [varchar](50), [Boy] [varchar](50), [Aciklama] [varchar](300), [AksesuarKaliteId] [int], [MusteriKodu] [varchar](500), [UreticiKodu] [varchar](500), [OriginId] [int], [ModifiedOn] [datetime], [TS] [varbinary], [Deleted] [bit])");

            Session.Init(new Options(), SavedLookups, (int)Rp.V_User);
            DevMainForm.BarcodeComPort = ConfExpert.Properties.Settings.Default.BarcodeComPort;
            DevMainForm.BarcodeEnabled = ConfExpert.Properties.Settings.Default.BarcodeEnabled;
        }
    }
}
